/**
 * 配置管理器
 * 负责加载和应用网站配置
 */
class ConfigManager {
    constructor() {
        this.config = null;
        this.defaultConfig = this.getDefaultConfig();
    }

    /**
     * 获取默认配置
     */
    getDefaultConfig() {
        return {
            site: {
                title: "极客终端 | 个人博客",
                author: "极客开发者"
            },
            profile: {
                name: "极客开发者",
                title: "全栈工程师 / 游戏开发者"
            }
        };
    }

    /**
     * 加载配置文件
     */
    async loadConfig() {
        try {
            const response = await fetch('./config/site-config.json');
            if (response.ok) {
                this.config = await response.json();
                console.log('配置文件加载成功');
                return this.config;
            } else {
                console.warn('配置文件加载失败，使用默认配置');
                this.config = this.defaultConfig;
                return this.config;
            }
        } catch (error) {
            console.error('配置文件加载错误:', error);
            this.config = this.defaultConfig;
            return this.config;
        }
    }

    /**
     * 应用网站基础配置
     */
    applySiteConfig() {
        if (!this.config) return;

        const { site, profile } = this.config;

        // 更新页面标题
        if (site.title) {
            document.title = site.title;
        }

        // 更新meta标签
        if (site.description) {
            this.updateMetaTag('description', site.description);
        }
        if (site.keywords) {
            this.updateMetaTag('keywords', site.keywords);
        }
        if (site.author) {
            this.updateMetaTag('author', site.author);
        }

        // 更新终端标题
        const terminalTitle = document.querySelector('.terminal-title');
        if (terminalTitle && profile.name) {
            terminalTitle.innerHTML = `root@${profile.name.toLowerCase().replace(/\s+/g, '-')}:~# <span class="blink">_</span>`;
        }
    }

    /**
     * 应用个人资料配置
     */
    applyProfileConfig() {
        if (!this.config || !this.config.profile) return;

        const { profile } = this.config;

        // 更新个人信息
        const nameElement = document.querySelector('.typing-text p:nth-child(1) .highlight');
        if (nameElement && profile.name) {
            nameElement.textContent = profile.name;
        }

        const titleElement = document.querySelector('.typing-text p:nth-child(2) .highlight');
        if (titleElement && profile.title) {
            titleElement.textContent = profile.title;
        }

        const skillsElement = document.querySelector('.typing-text p:nth-child(3) .highlight');
        if (skillsElement && profile.skills) {
            skillsElement.textContent = profile.skills;
        }

        const statusElement = document.querySelector('.typing-text p:nth-child(4) .highlight');
        if (statusElement && profile.status) {
            statusElement.textContent = profile.status;
        }
    }

    /**
     * 应用统计数据配置
     */
    applyStatsConfig() {
        if (!this.config || !this.config.stats) return;

        const { stats } = this.config;

        Object.keys(stats).forEach((key, index) => {
            const stat = stats[key];
            const statBox = document.querySelectorAll('.stat-box')[index];

            if (statBox) {
                const titleElement = statBox.querySelector('.stat-title');
                const valueElement = statBox.querySelector('.stat-value');
                const progressBar = statBox.querySelector('.progress-bar');

                if (titleElement && stat.label) {
                    titleElement.textContent = stat.label;
                }
                if (valueElement && stat.value) {
                    valueElement.textContent = stat.value;
                }
                if (progressBar && stat.progress) {
                    progressBar.style.width = `${stat.progress}%`;
                }
            }
        });
    }

    /**
     * 应用活动日志配置
     */
    applyActivitiesConfig() {
        if (!this.config || !this.config.activities) return;

        const { activities } = this.config;
        const activityLog = document.querySelector('.activity-log');

        if (activityLog) {
            activityLog.innerHTML = '';

            activities.forEach(activity => {
                const logEntry = document.createElement('div');
                logEntry.className = 'log-entry';

                logEntry.innerHTML = `
                    <span class="log-time">${activity.time}</span>
                    <span class="log-type ${activity.type}">${activity.type.toUpperCase()}</span>
                    <span class="log-message">${activity.message}</span>
                `;

                activityLog.appendChild(logEntry);
            });
        }
    }

    /**
     * 应用项目配置
     */
    applyProjectsConfig() {
        if (!this.config || !this.config.projects) return;

        const { projects } = this.config;
        const projectsGrid = document.querySelector('.projects-grid');

        if (projectsGrid) {
            projectsGrid.innerHTML = '';

            projects.forEach(project => {
                const projectCard = document.createElement('div');
                projectCard.className = 'project-card';
                projectCard.dataset.category = project.category;

                const techTags = project.technologies.map(tech =>
                    `<span class="tech">${tech}</span>`
                ).join('');

                const categoryTags = `<span class="mini-tag">${this.getCategoryLabel(project.category)}</span>`;

                projectCard.innerHTML = `
                    <div class="card-inner">
                        <div class="card-front">
                            <div class="project-icon"><i class="${project.icon}"></i></div>
                            <h3>${project.name}</h3>
                            <div class="project-tags">
                                ${categoryTags}
                            </div>
                        </div>
                        <div class="card-back">
                            <h3>${project.name}</h3>
                            <p>${project.description}</p>
                            <div class="tech-stack">
                                ${techTags}
                            </div>
                            <a href="${project.link}" class="project-link">查看项目 <i class="fas fa-external-link-alt"></i></a>
                        </div>
                    </div>
                `;

                projectsGrid.appendChild(projectCard);
            });
        }
    }

    /**
     * 应用时间线配置
     */
    applyTimelineConfig() {
        if (!this.config || !this.config.timeline) return;

        const { timeline } = this.config;
        const timelineContainer = document.querySelector('.timeline-container');

        if (timelineContainer) {
            // 保留时间线样式，只更新内容
            const existingNodes = timelineContainer.querySelectorAll('.timeline-node');
            existingNodes.forEach(node => node.remove());

            timeline.forEach(item => {
                const timelineNode = document.createElement('div');
                timelineNode.className = 'timeline-node';

                const descriptions = item.description.map(desc => `<p>${desc}</p>`).join('');
                const techTags = item.technologies.map(tech =>
                    `<span class="tech">${tech}</span>`
                ).join('');

                timelineNode.innerHTML = `
                    <div class="timeline-date">${item.period}</div>
                    <div class="timeline-content">
                        <h3>${item.position}</h3>
                        <h4>${item.company}</h4>
                        <div class="timeline-details">
                            ${descriptions}
                            ${techTags ? `<div class="tech-used">${techTags}</div>` : ''}
                        </div>
                    </div>
                `;

                timelineContainer.appendChild(timelineNode);
            });
        }
    }

    /**
     * 应用技能配置
     */
    applySkillsConfig() {
        if (!this.config || !this.config.skills) return;

        const { skills } = this.config;

        // 更新技能进度条
        if (skills.bars) {
            const skillBarsContainer = document.querySelector('.skill-bars-container');
            if (skillBarsContainer) {
                skillBarsContainer.innerHTML = '';

                skills.bars.forEach(skill => {
                    const skillItem = document.createElement('div');
                    skillItem.className = 'skill-bar-item';

                    const stars = Array.from({ length: 5 }, (_, i) => {
                        const starClass = i < skill.level ? 'fas fa-star' : 'far fa-star';
                        return `<i class="${starClass}"></i>`;
                    }).join('');

                    skillItem.innerHTML = `
                        <div class="skill-bar-header">
                            <span class="skill-name">${skill.name}</span>
                            <span class="skill-percentage">${skill.percentage}%</span>
                        </div>
                        <div class="skill-bar-bg">
                            <div class="skill-bar-fill" style="width: ${skill.percentage}%"></div>
                        </div>
                        <div class="skill-level">
                            <div class="skill-stars">
                                ${stars}
                            </div>
                        </div>
                    `;

                    skillBarsContainer.appendChild(skillItem);
                });
            }
        }

        // 雷达图数据将在main.js中使用
        if (skills.radar) {
            window.configSkillsRadar = skills.radar;
        }
    }

    /**
     * 应用主题配置
     */
    applyThemeConfig() {
        if (!this.config || !this.config.theme) return;

        const { theme } = this.config;
        const root = document.documentElement;

        if (theme.primaryColor) {
            root.style.setProperty('--accent-color', theme.primaryColor);
        }
        if (theme.secondaryColor) {
            root.style.setProperty('--accent-color-alt', theme.secondaryColor);
        }
        if (theme.backgroundColor) {
            root.style.setProperty('--bg-color', theme.backgroundColor);
        }
        if (theme.textColor) {
            root.style.setProperty('--text-color', theme.textColor);
        }
        if (theme.fontFamily) {
            root.style.setProperty('--font-mono', theme.fontFamily);
        }
    }

    /**
     * 应用机器人配置
     */
    applyRobotConfig() {
        if (!this.config || !this.config.robot) return;

        const { robot } = this.config;

        // 如果禁用机器人，隐藏它
        const petRobot = document.getElementById('pet-robot');
        if (petRobot) {
            petRobot.style.display = robot.enabled ? 'block' : 'none';
        }

        // 更新机器人的技术知识库
        if (robot.techFacts && window.updateRobotTechFacts) {
            window.updateRobotTechFacts(robot.techFacts);
        }
    }

    /**
     * 应用特效配置
     */
    applyEffectsConfig() {
        if (!this.config || !this.config.effects) return;

        const { effects } = this.config;

        // 数字雨配置
        if (effects.matrixRain && window.matrixRain) {
            if (!effects.matrixRain.enabled) {
                const canvas = document.getElementById('matrix-rain');
                if (canvas) canvas.style.display = 'none';
            } else {
                window.matrixRain.setDensity(effects.matrixRain.density);
                if (effects.matrixRain.characters) {
                    window.matrixRain.characters = effects.matrixRain.characters;
                }
            }
        }

        // 粒子系统配置
        if (effects.particles && window.particleSystem) {
            window.particleSystem.setActive(effects.particles.enabled);
            if (effects.particles.maxParticles) {
                window.particleSystem.maxParticles = effects.particles.maxParticles;
            }
        }

        // 故障效果配置
        if (effects.glitch && window.effectsSystem) {
            if (effects.glitch.frequency) {
                window.effectsSystem.glitchFrequency = effects.glitch.frequency;
            }
        }

        // 动画速度配置
        if (effects.animations && effects.animations.speed) {
            document.documentElement.style.setProperty('--animation-speed-factor', 11 - effects.animations.speed);
        }
    }

    /**
     * 获取分类标签
     */
    getCategoryLabel(category) {
        const labels = {
            'game': '游戏',
            'web': 'Web',
            'ai': 'AI',
            'mobile': '移动端'
        };
        return labels[category] || category;
    }

    /**
     * 更新meta标签
     */
    updateMetaTag(name, content) {
        let meta = document.querySelector(`meta[name="${name}"]`);
        if (!meta) {
            meta = document.createElement('meta');
            meta.name = name;
            document.head.appendChild(meta);
        }
        meta.content = content;
    }

    /**
     * 初始化配置管理器
     */
    async init() {
        await this.loadConfig();

        // 应用所有配置
        this.applySiteConfig();
        this.applyProfileConfig();
        this.applyStatsConfig();
        this.applyActivitiesConfig();
        this.applyProjectsConfig();
        this.applyTimelineConfig();
        this.applySkillsConfig();
        this.applyThemeConfig();
        this.applyRobotConfig();

        // 延迟应用特效配置，确保其他脚本已加载
        setTimeout(() => {
            this.applyEffectsConfig();
        }, 1000);

        console.log('所有配置已应用');
        return this.config;
    }

    /**
     * 获取配置值
     */
    get(path) {
        if (!this.config) return null;

        return path.split('.').reduce((obj, key) => {
            return obj && obj[key] !== undefined ? obj[key] : null;
        }, this.config);
    }

    /**
     * 设置配置值
     */
    set(path, value) {
        if (!this.config) return;

        const keys = path.split('.');
        const lastKey = keys.pop();
        const target = keys.reduce((obj, key) => {
            if (!obj[key]) obj[key] = {};
            return obj[key];
        }, this.config);

        target[lastKey] = value;
    }

    /**
     * 导出配置
     */
    exportConfig() {
        return JSON.stringify(this.config, null, 2);
    }

    /**
     * 导入配置
     */
    async importConfig(configJson) {
        try {
            const newConfig = JSON.parse(configJson);
            this.config = { ...this.config, ...newConfig };

            // 重新应用配置
            await this.init();

            return true;
        } catch (error) {
            console.error('配置导入失败:', error);
            return false;
        }
    }
}

// 创建全局配置管理器实例
window.configManager = new ConfigManager();

// 在DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', async () => {
    await window.configManager.init();
});